package com.ebeitech.doorapp.view.setting;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.domain.AppInfo;
import com.ebeitech.doorapp.domain.dao.AppInfoDao;
import com.ebeitech.doorapp.http.EbeiErrorCode;
import com.ebeitech.doorapp.http.HttpListener;
import com.ebeitech.doorapp.http.HttpService;
import com.ebeitech.doorapp.http.model.BaseModel;
import com.ebeitech.doorapp.http.service.HttpOperateServiceRx;
import com.ebeitech.doorapp.util.image.GlideRoundTransform;
import com.ebeitech.doorapp.view.BaseActivity;
import com.ebeitech.doorapp.view.customviews.RoundPercentTextView;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.CommonTitleBar;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.util.CommonUtil;
import com.ebeitech.library.util.FileUtil;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;
import com.ebeitech.library.util.ZipUtil;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;

/**
 * Created by alice on 2017/11/1.
 */
public class AppManageActivity extends BaseActivity {

	@BindView(R.id.tvTitle)
	TextView mTitleView;
	@BindView(R.id.view_title)
	CommonTitleBar mTitleBarView;
	@BindView(R.id.listView)
	ListView mListView;

	private Context mContext;
	private APPListAdapter mAdapter;
	private List<ContentItem> mDatas = new ArrayList<ContentItem>();
	private Map<String, AppInfo> mAppInfoMap = new HashMap<String, AppInfo>();

	private String mUserId;

	private HttpService mHttpService;
	private CommonAlertDialogFragment mProgressDialog;

	@Override
	protected void onCreate(Bundle arg0) {
		if (arg0 == null) {
			arg0 = new Bundle();
		}
		arg0.putBoolean(SPConstants.IS_FIT_STATUS_BAR, false);
		super.onCreate(arg0);
		setContentView(R.layout.ebei_activity_listview);
		ButterKnife.bind(this);
		mContext = this;
		mUserId = StringUtil.getDefaultString(SPManager.getInstance(mContext).get(SPConstants.USER_ID, ""));
		mHttpService = HttpService.getInstance();

		initView();
		loadAppList();
	}

	private void initView() {
		mTitleView.setText(R.string.ebei_app_manage);

		mAdapter = new APPListAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setBackgroundResource(R.color.ebei_activity_bg);
		mListView.setDivider(null);
	}

	private void loadAppList() {
		HttpOperateServiceRx mHttpOperateServiceRx = mHttpService.getRxGsonRetrofit().create(HttpOperateServiceRx.class);
		final Call<ResponseBody> call = mHttpOperateServiceRx.doLoadAppList();
		final CommonAlertDialogFragment mProgressDialog = ViewUtil.showProgressDialog(mContext);
		mHttpService.executeHttp(mContext, call, new HttpListener<BaseModel>() {

			private List<ContentItem> datas = new ArrayList<ContentItem>();
			private Map<String, AppInfo> appMap = new HashMap<String, AppInfo>();

			@Override
			public void onDoInBackground(BaseModel result) {
				super.onDoInBackground(result);
				Map<String, List<AppInfo>> map = new HashMap<>();
				try {
					if (result != null) {
						Object retData = result.getRetData();
						JSONArray jsonArray = new JSONArray(new Gson().toJson(retData));
						for (int i = 0; i < jsonArray.length(); i++) {
							AppInfo appInfo = new AppInfo();
							appInfo.initWithJson(jsonArray.optString(i));

							List<AppInfo> appInfos = map.get(appInfo.getGroupId());
							if (appInfos == null) {
								appInfos = new ArrayList<AppInfo>();
								map.put(appInfo.getGroupId(), appInfos);

								ContentItem item = new ContentItem();
								item.setGroupName(appInfo.getGroupName());
								item.setAppInfos(appInfos);
								datas.add(item);
							}
							appInfos.add(appInfo);
						}
					}

					List<AppInfo> list = AppInfoDao.getInstance().getAppList(null);
					for (AppInfo item : list) {
						appMap.put(item.getAppId(), item);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				ViewUtil.dismissDialog(mProgressDialog);
			}

			@Override
			public void onSuccess(BaseModel result) {
				ViewUtil.dismissDialog(mProgressDialog);

				mDatas.clear();
				mDatas.addAll(datas);
				mAppInfoMap.clear();
				mAppInfoMap.putAll(appMap);
				mAdapter.notifyDataSetChanged();
			}
		}, BaseModel.class, false);
	}

	class APPListAdapter extends BaseAdapter {

		private int margin;
		private int itemWidth;
		private Map<String, Boolean> mContentVisibleMap = new HashMap<String, Boolean>();

		private Handler mHandler = new Handler(Looper.getMainLooper()) {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				RoundPercentTextView roundPercentTextView = (RoundPercentTextView) msg.obj;
				Integer rate = roundPercentTextView.getTag() == null ? 0 : (Integer) roundPercentTextView.getTag();
				roundPercentTextView.setRate((float) rate);
			}
		};

		public APPListAdapter() {
			margin = ViewUtil.dp2px(mContext, 10);
		}

		@Override
		public int getCount() {
			return mDatas.size();
		}

		@Override
		public Object getItem(int position) {
			return mDatas.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder viewHolder;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_title_item, null);
				viewHolder.tvName = (TextView) convertView.findViewById(R.id.tvName);
				viewHolder.viewContent = (LinearLayout) convertView.findViewById(R.id.view_content);
				viewHolder.arrowView = (ImageView) convertView.findViewById(R.id.view_arrow);
				convertView.findViewById(R.id.view_divider).setVisibility(View.VISIBLE);
				viewHolder.viewContent.setVisibility(View.VISIBLE);
				viewHolder.arrowView.setVisibility(View.VISIBLE);
				convertView.setTag(viewHolder);
				convertView.setPadding(0, 0, 0, margin);
				if (itemWidth == 0) {
					itemWidth = (ViewUtil.getScreenSize((Activity) mContext).widthPixels - ViewUtil.dp2px(mContext, 20)) / 4;
				}
				LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) viewHolder.arrowView.getLayoutParams();
				lp.width = ViewUtil.dp2px(mContext, 25);
				viewHolder.arrowView.setLayoutParams(lp);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			ContentItem contentItem = mDatas.get(position);
			convertView.findViewById(R.id.view_title).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					if (viewHolder.viewContent.getVisibility() == View.VISIBLE) {
						viewHolder.viewContent.setVisibility(View.GONE);
						mContentVisibleMap.put(contentItem.getGroupName(), false);
						viewHolder.arrowView.setImageResource(R.drawable.ebei_btn_arrow_down);
					} else {
						viewHolder.viewContent.setVisibility(View.VISIBLE);
						mContentVisibleMap.put(contentItem.getGroupName(), false);
						viewHolder.arrowView.setImageResource(R.drawable.ebei_btn_arrow_up);
					}
				}
			});

			viewHolder.tvName.setText(contentItem.getGroupName());
			boolean isVisible = mContentVisibleMap.containsKey(contentItem.getGroupName()) ?  mContentVisibleMap.get(contentItem.getGroupName()) : true;
			if (isVisible) {
				viewHolder.arrowView.setImageResource(R.drawable.ebei_btn_arrow_up);
			} else {
				viewHolder.arrowView.setImageResource(R.drawable.ebei_btn_arrow_down);
			}
			List<AppInfo> appInfos = contentItem.getAppInfos();
			LinearLayout parentView = (LinearLayout) viewHolder.viewContent;
			parentView.setPadding(0, 0, 0, 0);
			viewHolder.viewContent.removeAllViews();
			for (int i = 0; i < appInfos.size(); i++) {
				final AppInfo appInfo = appInfos.get(i);
				View itemView = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_app_item, null);
				ImageView logoImage = (ImageView) itemView.findViewById(R.id.ivLogo);
				int width = ViewUtil.getScreenSize(AppManageActivity.this).widthPixels / 4 / 2;
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, width);
				logoImage.setLayoutParams(lp);
				Glide.with(mContext).load(appInfo.getAppLogo()).placeholder(R.color.ebei_transparent).transform(new GlideRoundTransform(mContext)).into(logoImage);
				TextView appNameText = (TextView) itemView.findViewById(R.id.tvAppName);
				appNameText.setText(appInfo.getAppName());
				TextView appTimeText = (TextView) itemView.findViewById(R.id.tvAppTime);
				String updateTime = appInfo.getUpdateTime();
				if (!StringUtil.isStringNullOrEmpty(updateTime)) {
					updateTime = com.ebeitech.doorapp.qqim.util.TimeUtil.getChatTimeShortStrWithTimeMillis(TimeUtil.getTimeMillis(updateTime));
				} else {
					updateTime = "";
				}
				appTimeText.setText(updateTime);
				final View topView = itemView.findViewById(R.id.view_top);
				final View infoView = itemView.findViewById(R.id.view_info);
				boolean isAppVisible = mContentVisibleMap.containsKey("appId-" + appInfo.getAppId()) ?  mContentVisibleMap.get("appId-" + appInfo.getAppId()) : false;
				if (isAppVisible) {
					infoView.setVisibility(View.VISIBLE);
				} else {
					infoView.setVisibility(View.GONE);
				}
				topView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (infoView.getVisibility() == View.VISIBLE) {
							infoView.setVisibility(View.GONE);
							mContentVisibleMap.put("appId-" + appInfo.getAppId(), false);
						} else {
							infoView.setVisibility(View.VISIBLE);
							mContentVisibleMap.put("appId-" + appInfo.getAppId(), true);
						}
					}
				});
				TextView projectNameText = (TextView) itemView.findViewById(R.id.tvProjectName);
				projectNameText.setText("所属公司：" + appInfo.getCompanyName());
				TextView appDescText = (TextView) itemView.findViewById(R.id.tvAppDesc);
				appDescText.setText("描述：" + appInfo.getAppDesc());
				final Button loadBtn = (Button) itemView.findViewById(R.id.btnLoad);
				Button uninstallBtn = (Button) itemView.findViewById(R.id.btnUninstall);
				if (AppInfo.APP_TYPE_OFFLINE.equals(appInfo.getAppType())) {
					String saveFile = CommonUtil.getAppLoadFile(mContext, appInfo.getAppId());
					String url = saveFile + File.separator + "index.html";
					if (FileUtil.fileExist(url)) {
						String localVersion = "";
						if (mAppInfoMap.containsKey(appInfo.getAppId())) {
							localVersion = mAppInfoMap.get(appInfo.getAppId()).getVersion();
						}
						if (!StringUtil.isStringNullOrEmpty(localVersion) && !localVersion.equals(appInfo.getVersion())) {
							loadBtn.setTextAppearance(mContext, R.style.EbeiButtonBlue);
							loadBtn.setText("更新");
						} else {
							loadBtn.setBackgroundResource(R.color.ebei_transparent);
							loadBtn.setTextColor(getResources().getColor(R.color.ebei_text_common));
							loadBtn.setText("已安装");
							loadBtn.setPadding(0, 0, 0, 0);
						}
					} else {
						loadBtn.setTextAppearance(mContext, R.style.EbeiButtonBlue);
						loadBtn.setText("下载");
					}
					loadBtn.setVisibility(View.VISIBLE);
					if ("下载".equals(loadBtn.getText().toString())) {
						uninstallBtn.setVisibility(View.INVISIBLE);
					} else {
						uninstallBtn.setVisibility(View.VISIBLE);
					}
				} else {
					loadBtn.setVisibility(View.INVISIBLE);
					uninstallBtn.setVisibility(View.INVISIBLE);
				}
				RoundPercentTextView roundPercentTextView = (RoundPercentTextView) itemView.findViewById(R.id.roundPercentTextView);
				roundPercentTextView.setVisibility(View.GONE);
				View dividerView = itemView.findViewById(R.id.view_divider);
				if (i < appInfos.size() - 1) {
					dividerView.setVisibility(View.VISIBLE);
				} else {
					dividerView.setVisibility(View.GONE);
				}
				parentView.addView(itemView);

				loadBtn.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (!"下载".equals(loadBtn.getText().toString()) && !"更新".equals(loadBtn.getText().toString())) {
							return;
						}

						loadBtn.setVisibility(View.GONE);
						String saveFile = CommonUtil.getAppLoadFile(mContext, appInfo.getAppId());
						String downloadFile = CommonUtil.getCacheFile(mContext) + File.separator + appInfo.getAppId() + ".zip";
						// 下载APP
						FileUtil.deleteFile(saveFile);
						FileUtil.deleteFile(downloadFile);
						roundPercentTextView.setVisibility(View.VISIBLE);
						roundPercentTextView.setRate(0f);
						mHttpService.downloadFile(mContext, new HttpListener<String>() {

							@Override
							public void onError(EbeiErrorCode errorCode) {
								roundPercentTextView.setVisibility(View.GONE);
								loadBtn.setVisibility(View.VISIBLE);
							}

							@Override
							public void onDoInBackground(String result) {
								super.onDoInBackground(result);
								String downloadFile = CommonUtil.getCacheFile(mContext) + File.separator + appInfo.getAppId() + ".zip";
								String saveFile = CommonUtil.getAppLoadFile(mContext);
								try {
									ZipUtil.unzip(downloadFile, saveFile, false);
								} catch (Exception e) {
									e.printStackTrace();
								}
								AppInfoDao.getInstance().insertOrUpdate(appInfo);
								mAppInfoMap.put(appInfo.getAppId(), appInfo);
							}

							@Override
							public void onSuccess(String result) {
								roundPercentTextView.setVisibility(View.GONE);
								loadBtn.setVisibility(View.VISIBLE);
								mAdapter.notifyDataSetChanged();
							}
						}, new HttpService.HttpLoadListener() {
							@Override
							public void onLoad(float progress) {
								roundPercentTextView.setTag((int) progress);
								Message message = Message.obtain();
								message.obj = roundPercentTextView;
								mHandler.sendMessage(message);
							}
						}, appInfo.getAppUrl(), downloadFile);
					}
				});

				uninstallBtn.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						ViewUtil.showAlertDialog(mContext, getString(R.string.ebei_tips),
								getString(R.string.ebei_dialog_confirm_x_remind, (getString(R.string.ebei_uninstall) + appInfo.getAppName())),
								new CommonAlertDialogFragment.OnBtnClickListener() {
									@Override
									public void onClick(View v, CommonAlertDialogFragment dialog) {
										ViewUtil.dismissDialog(dialog);
										if (!isFinishing()) {
											mProgressDialog = ViewUtil.showProgressDialog(mContext);
										}
										new AsyncTask<Void, Void, Void>() {
											@Override
											protected Void doInBackground(Void... voids) {
												String saveFile = CommonUtil.getAppLoadFile(mContext, appInfo.getAppId());
												String downloadFile = CommonUtil.getCacheFile(mContext) + File.separator + appInfo.getAppId() + ".zip";
												FileUtil.deleteFile(saveFile);
												FileUtil.deleteFile(downloadFile);
												return null;
											}

											@Override
											protected void onPostExecute(Void aVoid) {
												super.onPostExecute(aVoid);
												if (!isFinishing()) {
													ViewUtil.dismissDialog(mProgressDialog);
												}
												mAdapter.notifyDataSetChanged();
											}
										}.execute();
									}
								}, null);
					}
				});
			}

			return convertView;
		}

		class ViewHolder {
			TextView tvName;
			ViewGroup viewContent;
			ImageView arrowView;
		}
	}

	class ContentItem {
		private String groupName;
		private List<AppInfo> appInfos;

		public String getGroupName() {
			return groupName;
		}

		public void setGroupName(String groupName) {
			this.groupName = groupName;
		}

		public List<AppInfo> getAppInfos() {
			if (appInfos == null) {
				appInfos = new ArrayList<AppInfo>();
			}
			return appInfos;
		}

		public void setAppInfos(List<AppInfo> appInfos) {
			this.appInfos = appInfos;
		}
	}

}
